//
//  CommentViewController.m
//  BJYShoppingMall
//
//  Created by Coder on 16/1/29.
//  Copyright © 2016年 BJY12. All rights reserved.
//

#import "CommentViewController.h"
#import "VPImageCropperViewController.h"
#import <MobileCoreServices/MobileCoreServices.h>
#import "UIBarButtonItem+CommomBarButtonItem.h"

#define ORIGINAL_MAX_WIDTH 640.0f

@interface CommentViewController ()<UITextFieldDelegate,HttpRequestDelegate,UIActionSheetDelegate,UIImagePickerControllerDelegate,VPImageCropperDelegate,UINavigationControllerDelegate,UITextViewDelegate>
{
    NSArray * btnArray;
    NSArray * btnPingJiaArray;
    NSDictionary * dic;
    NSString * score;
    
    UIButton * starButton;
    BeseHttpClient * request;
    NSInteger btnIndex;
    NSInteger imgBtnIndex;
    
    NSString * imgpath1;
    NSString * imgpath2;
    NSString * imgpath3;
    
    BOOL isfirst;
    
    NSMutableArray * imgPathArray;
}
@property (weak, nonatomic) IBOutlet UIImageView *img_product;
@property (weak, nonatomic) IBOutlet UIButton *btn_haoping;
@property (weak, nonatomic) IBOutlet UIButton *btn_zhongping;
@property (weak, nonatomic) IBOutlet UIButton *btn_chaping;
@property (weak, nonatomic) IBOutlet UITextView *tf_comment;

@property (weak, nonatomic) IBOutlet UIImageView *img_1;
@property (weak, nonatomic) IBOutlet UIImageView *img_2;
@property (weak, nonatomic) IBOutlet UIImageView *img_3;

@property (weak, nonatomic) IBOutlet UIButton *btn_1;
@property (weak, nonatomic) IBOutlet UIButton *btn_2;
@property (weak, nonatomic) IBOutlet UIButton *btn_3;

@property (weak, nonatomic) IBOutlet UIButton *btn_send;
@property (weak, nonatomic) IBOutlet UILabel *lable_count;
@property (weak, nonatomic) IBOutlet UILabel *label_text;


@end

@implementation CommentViewController


- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title =@"评价晒单";
    isfirst = YES;
    [self loadUserData];
    [self initview];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}
- (void)setNavigationbar
{
    self.navigationItem.title=@"登录";
    
    //设置返回按钮，让其返回主界面
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem createBackBBTframe:CGRectMake(0, 0, 80, self.navigationController.navigationBar.bounds.size.height) isShowArrow:YES isShowTitle:NO target:self action:@selector(backToHomeBar:)];
}
//设置返回按钮，让其返回主界面
-(IBAction)backToHomeBar:(id)sender
{
    NSLog(@"返回键的设置");
    //不使用过多的设置，耦合性太高不利于当前界面的复用
    //UITabBarController *tabCon= [AppDelegate getAPPDelegate].tabBarController;
    //tabCon.selectedIndex=0;
    //[self.navigationController popToRootViewControllerAnimated:YES];
    
    //APP的登录窗口为了复用应该使用模态弹出方式
    [self dismissViewControllerAnimated:YES completion:nil];
}



-(void)initview{
    
    //确定按钮
    _btn_send = [self setSendBtn:_btn_send];
    
    //改变输入框颜色
    _tf_comment.layer.borderColor = [UIColor lightGrayColor].CGColor;
    _tf_comment.layer.borderWidth =1.0;
    _tf_comment.layer.cornerRadius =6.0;
    
    //好评
    [_btn_haoping setImage:[UIImage imageNamed:@"iconfont_haoping2"] forState:UIControlStateNormal];
    [_btn_haoping setImage:[UIImage imageNamed:@"iconfont_haoping"]  forState:UIControlStateSelected];
    [_btn_haoping addTarget:self action:@selector(checkboxClick:)forControlEvents:UIControlEventTouchUpInside];
    [_btn_haoping setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
    [_btn_haoping setTitleColor:[UIColor redColor] forState:UIControlStateSelected];
    [_btn_haoping.imageView setContentMode:UIViewContentModeCenter];
    [_btn_haoping setTag:10001];
    [_btn_haoping setSelected:YES];
    
    //中评
    [_btn_zhongping setImage:[UIImage imageNamed:@"iconfont_zhongping2"] forState:UIControlStateNormal];
    [_btn_zhongping setImage:[UIImage imageNamed:@"iconfont_zhongping"]  forState:UIControlStateSelected];
    [_btn_zhongping setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
    [_btn_zhongping setTitleColor:[UIColor yellowColor] forState:UIControlStateSelected];
    [_btn_zhongping addTarget:self action:@selector(checkboxClick:)forControlEvents:UIControlEventTouchUpInside];
    [_btn_zhongping setTag:10002];
    
    //差评
    [_btn_chaping setImage:[UIImage imageNamed:@"iconfont_chaping2"] forState:UIControlStateNormal];
    [_btn_chaping setImage:[UIImage imageNamed:@"iconfont_chaping"]  forState:UIControlStateSelected];
    [_btn_chaping setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
    [_btn_chaping setTitleColor:[UIColor blackColor] forState:UIControlStateSelected];
    [_btn_chaping addTarget:self action:@selector(checkboxClick:)forControlEvents:UIControlEventTouchUpInside];
    [_btn_chaping setTag:10003];

    
    
    //上传图1
    [_btn_1 addTarget:self action:@selector(upLoadImgClick:)forControlEvents:UIControlEventTouchUpInside];
    [_btn_1 setTag:101];
    //上传图2
    [_btn_2 addTarget:self action:@selector(upLoadImgClick:)forControlEvents:UIControlEventTouchUpInside];
    [_btn_2 setTag:102];
    //上传图3
    [_btn_3 addTarget:self action:@selector(upLoadImgClick:)forControlEvents:UIControlEventTouchUpInside];
    [_btn_3 setTag:103];
    
    btnPingJiaArray = @[_btn_haoping,_btn_haoping,_btn_haoping];
    btnArray = @[_btn_1,_btn_2,_btn_3];
    imgPathArray = [[NSMutableArray alloc]init];
    
    #pragma mark - 输入框自定义
    //内容对齐方式
    _tf_comment.textAlignment = UITextAlignmentLeft;
//    _tf_comment.contentVerticalAlignment = UIControlContentVerticalAlignmentTop;
//    //设置为YES时文本会自动缩小以适应文本窗口大小.默认是保持原来大小,而让长文本滚动
//    _tf_comment.adjustsFontSizeToFitWidth = YES;
//    
    //设置代理 用于实现协议
    _tf_comment.delegate = self;
//    [_tf_comment addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    _label_text.enabled = NO;//lable必须设置为不可用
    

    
    //添加手势隐藏输入框
    self.view.userInteractionEnabled = YES;
    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(fingerTapped:)];
    
    [self.view addGestureRecognizer:singleTap];
}
#pragma mark - UITextView代理
-(void)textViewDidChange:(UITextView *)textView
{
//    self.examineText =  textView.text;
    _tf_comment.editable = YES;

    if (textView.text.length == 0) {
        _label_text.text = @"    文字内容在1~200字之间";
        _lable_count.text = @"200";

    }
    if(textView.text.length >0 & textView.text.length <200){
        NSInteger count = 200 - textView.text.length;
        _lable_count.text = [NSString stringWithFormat:@"%d",count];
        
        _label_text.text = @"";
    }
    if(textView.text.length >=200)
    {
        [self showMessage:@"输入的文字不能超过两百字" time:2];
        [_tf_comment setSelectable:NO];
    }
    
    
}
#pragma mark - 隐藏输入框
-(void)fingerTapped:(UITapGestureRecognizer *)gestureRecognizer
{
    [self.view endEditing:YES];
    [_tf_comment setSelectable:YES];
}

#pragma mark - Action
-(void)checkboxClick:(UIButton*)btn{
    
    if(btn!=starButton){
        starButton.selected=NO;
        starButton=btn;
    }
    starButton.selected=YES;
    
//    btn.selected = !btn.selected;
    if(isfirst){
        isfirst = NO;
        _btn_haoping.selected=NO;
        
    }
}
//点击拍照
-(void)upLoadImgClick:(UIButton*)btn{
    btnIndex = btn.tag;
    [self makeUIActionSheet];
}
- (IBAction)submitAction:(id)sender {
    
    for (int i=1; i<btnPingJiaArray.count; i++) {
        UIButton * btnPingjia = [btnPingJiaArray objectAtIndex:i];
        if(btnPingjia.selected)
        {
            switch (btnPingjia.tag) {
                case 10001:
                    score = @"5";
                    break;
                case 10002:
                    score = @"3";
                    break;
                case 10003:
                    score = @"1";
                    break;
                default:
                    break;
            }
            
        }
    }
    
    
    if (score !=nil) {
        if (_tf_comment.text.length==0) {
            [self showMessage:@"评价内容不能为空" time:2];
        }else{
            [self uploadComment];
        }
    }else{
        [self showMessage:@"请点击商品评分" time:2];
    }
    
}
-(void)uploadComment
{
    
    if (!request) {
        request = [[BeseHttpClient alloc]init];
        request.delegate = self;
    }
    [self showProgressHUD];
    [request AddTradeComment:_userCookies
                     tradeId:[[[dic valueForKey:@"Array"] valueForKey:@"Data"] valueForKey:@"TradeID"]
                  experience:_tf_comment.text
                        Img1:imgpath1
                        Img2:imgpath2
                        Img3:imgpath3
                       score:score];
}

-(void)loadUserData
{
    if (!request) {
        request = [[BeseHttpClient alloc]init];
        request.delegate = self;
    }
    [self showProgressHUD];
    [request GetTradeApplicationByTradeId:_userCookies tradeid:_tradeid];
}

#pragma mark - metho
-(void)UploadHeadImg:(NSData*)imgData
{
    if (!request) {
        request = [[BeseHttpClient alloc]init];
        request.delegate = self;
    }
    [self showProgressHUD:@"正在上传相片"];
    [request UploadHeadImg:imgData andUID:[userDefaults valueForKey:USER_ID]];
}
#pragma mark - HTTPDelegate
-(void)HttpRequestSuccess:(NSMutableDictionary *)dictionary requestType:(NSString *)requestType
{
    [self hideProgressHUD];
    
    if ([requestType isEqualToString:HTTP_UploadHeadImg]) {
        if ([[dictionary objectForKey:@"state"] boolValue]) {
            
            switch (btnIndex) {
                case 101:
                    imgpath1 = [dictionary objectForKey:@"fileUrl"];
                    break;
                case 102:
                    imgpath2 = [dictionary objectForKey:@"fileUrl"];
                    break;
                case 103:
                    imgpath3 = [dictionary objectForKey:@"fileUrl"];
                    break;
                default:
                    break;
            }
            
        }
    }
    
    if ([requestType isEqualToString:HTTP_AddTradeComment]) {
        [self showMessage:[[dictionary valueForKey:@"Array"] valueForKey:@"Message"] time:2];
        if ([[dictionary valueForKey:@"Array"] valueForKey:@"Code"]) {
            //返回订单列表
            [self.navigationController popViewControllerAnimated:YES];
        }else{
            
        }
        
    }


    
    
    if ([requestType isEqualToString:HTTP_GetTradeApplicationByTradeId]) {
        dic = [[NSDictionary alloc]init];
        dic = dictionary;
        
        [userDefaults setValue:[[[dictionary valueForKey:@"Array"] valueForKey:@"Data"] valueForKey:@"UserID"] forKey:USER_ID];
        
        NSString * IMGstring = [[[dictionary valueForKey:@"Array"] valueForKey:@"Data"] valueForKey:@"Pic"];
        
        if ([IMGstring rangeOfString:@","].location != NSNotFound) {
            //冲一串图片列表中以逗号为分割点，截取后放入NSArray中
            NSArray *strarray = [IMGstring componentsSeparatedByString:@","];
            //产品图片
            [_img_product sd_setImageWithURL:[StaticMethod getImageUrlFromUrlString:strarray[1]] placeholderImage:[UIImage imageNamed:@"user_top_head"]];
            
        }else{
            [_img_product sd_setImageWithURL:[StaticMethod getImageUrlFromUrlString:IMGstring] placeholderImage:[UIImage imageNamed:@"user_top_head"]];
        }
        
        
    }

    
}
-(void)HttpRequestError:(NSError *)error
{
    [self hideProgressHUD];
    
}


#pragma mark - textFieldDeleage


#pragma mark UIActionSheet
-(void)makeUIActionSheet
{
    UIActionSheet *choiceSheet = [[UIActionSheet alloc] initWithTitle:nil
                                                             delegate:self
                                                    cancelButtonTitle:@"取消"
                                               destructiveButtonTitle:nil
                                                    otherButtonTitles:@"拍照", @"从相册中选取", nil];
    [choiceSheet showInView:self.view];
}

#pragma mark UIActionSheetDelegate
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
        // 拍照
        if ([self isCameraAvailable] && [self doesCameraSupportTakingPhotos]) {
            UIImagePickerController *controller = [[UIImagePickerController alloc] init];
            controller.sourceType = UIImagePickerControllerSourceTypeCamera;
            if ([self isFrontCameraAvailable]) {
                //前置摄像头或者后置摄像头
                controller.cameraDevice = UIImagePickerControllerCameraDeviceRear;
            }
            NSMutableArray *mediaTypes = [[NSMutableArray alloc] init];
            [mediaTypes addObject:(__bridge NSString *)kUTTypeImage];
            controller.mediaTypes = mediaTypes;
            controller.delegate = self;
            [self presentViewController:controller
                               animated:YES
                             completion:^(void){
                                 NSLog(@"Picker View Controller is presented");
                             }];
        }
        
    } else if (buttonIndex == 1) {
        // 从相册中选取
        if ([self isPhotoLibraryAvailable]) {
            UIImagePickerController *controller = [[UIImagePickerController alloc] init];
            controller.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            NSMutableArray *mediaTypes = [[NSMutableArray alloc] init];
            [mediaTypes addObject:(__bridge NSString *)kUTTypeImage];
            controller.mediaTypes = mediaTypes;
            controller.delegate = self;
            [self presentViewController:controller
                               animated:YES
                             completion:^(void){
                                 NSLog(@"Picker View Controller is presented");
                             }];
        }
    }
    
}
#pragma mark camera utility
- (BOOL) isCameraAvailable{
    return [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
}

- (BOOL) isRearCameraAvailable{
    return [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear];
}

- (BOOL) isFrontCameraAvailable {
    return [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceFront];
}

- (BOOL) doesCameraSupportTakingPhotos {
    return [self cameraSupportsMedia:(__bridge NSString *)kUTTypeImage sourceType:UIImagePickerControllerSourceTypeCamera];
}

- (BOOL) isPhotoLibraryAvailable{
    return [UIImagePickerController isSourceTypeAvailable:
            UIImagePickerControllerSourceTypePhotoLibrary];
}
- (BOOL) canUserPickVideosFromPhotoLibrary{
    return [self
            cameraSupportsMedia:(__bridge NSString *)kUTTypeMovie sourceType:UIImagePickerControllerSourceTypePhotoLibrary];
}
- (BOOL) canUserPickPhotosFromPhotoLibrary{
    return [self
            cameraSupportsMedia:(__bridge NSString *)kUTTypeImage sourceType:UIImagePickerControllerSourceTypePhotoLibrary];
}

- (BOOL) cameraSupportsMedia:(NSString *)paramMediaType sourceType:(UIImagePickerControllerSourceType)paramSourceType{
    __block BOOL result = NO;
    if ([paramMediaType length] == 0) {
        return NO;
    }
    NSArray *availableMediaTypes = [UIImagePickerController availableMediaTypesForSourceType:paramSourceType];
    [availableMediaTypes enumerateObjectsUsingBlock: ^(id obj, NSUInteger idx, BOOL *stop) {
        NSString *mediaType = (NSString *)obj;
        if ([mediaType isEqualToString:paramMediaType]){
            result = YES;
            *stop= YES;
        }
    }];
    return result;
}

#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [picker dismissViewControllerAnimated:YES completion:^() {
        UIImage *portraitImg = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
        portraitImg = [self imageByScalingToMaxSize:portraitImg];
        
            switch (btnIndex) {
                case 101:
                    [_img_1 setImage:portraitImg];
                    break;
                case 102:
                    [_img_2 setImage:portraitImg];
                    break;
                case 103:
                    [_img_3 setImage:portraitImg];
                    break;
                default:
                    break;
                    
            }
        //将UIImage调整压缩分辨率后转成NSData
        
        [self UploadHeadImg: [StaticMethod resetSizeOfImageData:portraitImg maxSize:300]];

        
       /* // 裁剪
        VPImageCropperViewController *imgEditorVC = [[VPImageCropperViewController alloc] initWithImage:portraitImg cropFrame:CGRectMake(0, 100.0f, self.view.frame.size.width, self.view.frame.size.width) limitScaleRatio:3.0];
        imgEditorVC.delegate = self;
        [self presentViewController:imgEditorVC animated:YES completion:^{
            // TO DO
        }];
        */
    }];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:^(){
    }];
}
#pragma mark VPImageCropperDelegate
//
- (void)imageCropper:(VPImageCropperViewController *)cropperViewController didFinished:(UIImage *)editedImage {
    //    self.portraitImageView.image = editedImage;
    NSLog(@"--imageCropper--");
    
    [cropperViewController dismissViewControllerAnimated:YES completion:^{
        // TO DO
        //将UIImage转成NSData
        [self UploadHeadImg: UIImagePNGRepresentation(editedImage)];
        
    }];
}

- (void)imageCropperDidCancel:(VPImageCropperViewController *)cropperViewController {
    NSLog(@"--imageCropperDidCancel--");
    
    [cropperViewController dismissViewControllerAnimated:YES completion:^{
        NSLog(@"--imageCropperDidCancel--");
    }];
}


#pragma mark image scale utility
- (UIImage *)imageByScalingToMaxSize:(UIImage *)sourceImage {
    if (sourceImage.size.width < ORIGINAL_MAX_WIDTH) return sourceImage;
    CGFloat btWidth = 0.0f;
    CGFloat btHeight = 0.0f;
    if (sourceImage.size.width > sourceImage.size.height) {
        btHeight = ORIGINAL_MAX_WIDTH;
        btWidth = sourceImage.size.width * (ORIGINAL_MAX_WIDTH / sourceImage.size.height);
    } else {
        btWidth = ORIGINAL_MAX_WIDTH;
        btHeight = sourceImage.size.height * (ORIGINAL_MAX_WIDTH / sourceImage.size.width);
    }
    CGSize targetSize = CGSizeMake(btWidth, btHeight);
    return [self imageByScalingAndCroppingForSourceImage:sourceImage targetSize:targetSize];
}

- (UIImage *)imageByScalingAndCroppingForSourceImage:(UIImage *)sourceImage targetSize:(CGSize)targetSize {
    UIImage *newImage = nil;
    CGSize imageSize = sourceImage.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    CGFloat targetWidth = targetSize.width;
    CGFloat targetHeight = targetSize.height;
    CGFloat scaleFactor = 0.0;
    CGFloat scaledWidth = targetWidth;
    CGFloat scaledHeight = targetHeight;
    CGPoint thumbnailPoint = CGPointMake(0.0,0.0);
    if (CGSizeEqualToSize(imageSize, targetSize) == NO)
    {
        CGFloat widthFactor = targetWidth / width;
        CGFloat heightFactor = targetHeight / height;
        
        if (widthFactor > heightFactor)
            scaleFactor = widthFactor; // scale to fit height
        else
            scaleFactor = heightFactor; // scale to fit width
        scaledWidth  = width * scaleFactor;
        scaledHeight = height * scaleFactor;
        
        // center the image
        if (widthFactor > heightFactor)
        {
            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
        }
        else
            if (widthFactor < heightFactor)
            {
                thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
            }
    }
    UIGraphicsBeginImageContext(targetSize); // this will crop
    CGRect thumbnailRect = CGRectZero;
    thumbnailRect.origin = thumbnailPoint;
    thumbnailRect.size.width  = scaledWidth;
    thumbnailRect.size.height = scaledHeight;
    
    [sourceImage drawInRect:thumbnailRect];
    
    newImage = UIGraphicsGetImageFromCurrentImageContext();
    if(newImage == nil) NSLog(@"could not scale image");
    
    //pop the context to get back to the default
    UIGraphicsEndImageContext();
    return newImage;
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


-(NSURL*)getImageUrlFromUrlString :(NSString*)origalUrl
{

    
    return [NSURL URLWithString:[@"http://f.zlc99.com/" stringByAppendingString:origalUrl]];
    
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
